% QuadBGsub.m -- Auxiliary MATLAB script for performing quadratic background
%   subtraction on QDM data. This script is called by QDMdataprocessing.m
%   
%  Reference: R.R. Fu, E.A. Lima, M.W.R. Volk, R. Trubko (2020) "High-sensitivity
%  moment magnetometry with the quantum diamond microscope,"  Geochemistry,
%  Geophysics, Geosystems.  
%
% -----------------------------------------------------------------------------------
%                       Matlab code by Roger R. Fu
%            Copyright (C) 2017-2020 Harvard Paleomagnetics Lab
% -----------------------------------------------------------------------------------

function [ imOut ] = QuadBGsub( imIn )
x = 1:size(imIn,2); y = 1:size(imIn,1);
[X,Y] = meshgrid(x,y);
[xData, yData, zData] = prepareSurfaceData( X, Y, imIn );

[fitout gof] = fit([xData, yData],zData, 'poly22');
cvals = coeffvalues(fitout);
fitFunction = cvals(1) + cvals(2)*X + cvals(3)*Y +...
     cvals(4)*X.*X + cvals(5)*X.*Y + cvals(6)*Y.*Y;
imOut = (imIn-fitFunction);

end

